<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 渠道管理
 */
class Source extends BasicAdmin
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $source = 'tp_source';
    public $member = 'tp_member';
    public $item = 'tp_vote_item';

    /**
     * 列表
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {

        $get = $this->request->get();
        $db = Db::name($this->source)
            ->alias('a')
            ->field('a.*');

        foreach (['name',] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $db->whereLike('a.' . $field, "%{$get[$field]}%");
            }
        }

        return parent::_list($db->order('a.id asc'), 'id');
    }


    //导出数据
    public function outItems()
    {
        $get = input();

        $name = '渠道数据';

        $filename = iconv("utf-8", "gb2312", $name) . '.xlsx'; // 重命名表
        header('Content-disposition: attachment; filename="' . \XLSXWriter::sanitize_filename($filename) . '"');
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');

        $db = Db::name($this->source)
            ->field('tag,name');

        $db->where([]);
        $db->order('id asc');
        $data = $db->select();

        $newData = array();
        foreach ($data as $one) {
            $one['view'] = Db::name($this->member)->where(['source' => $one['tag']])->count();
            $one['reg'] = Db::name($this->item)->where(['source' => $one['tag']])->count();
            unset($one['tag']);
            $newData[] = $one;
        }
        $header1 = array(array('渠道数据'));
        $header2 = array(array('渠道', '浏览量', '参与量'));
//        print_dump(array_merge($header1,$header2, $newData));

        $writer = new \XLSXWriter();

        $sheet1 = $name;
//        $rows = array(
//            array('数据'),
//            array('渠道', '浏览量', '报名量'),
//            array("渠道1", "111", "222"),
//            array("渠道2", "111", "333"),
//            array("渠道3", "111", "2222",),
//        );

        $rows = array_merge($header1, $header2, $newData);
        $writer->writeSheet($rows, $sheet1);
        $writer->writeToStdOut();
        $this->success('导出成功');


    }

    /**
     * 添加菜单
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        return $this->_form($this->source, 'form');
    }

    /**
     * 编辑
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $source = Db::name($this->source)->where(['id' => $id])->find();
            empty($source) && $this->error('需要编辑的不存在！');
            return $this->fetch('form', ['vo' => $source, 'title' => '编辑']);
        }
        try {
            $id = $this->request->post('id');
            $data = $this->request->post();
            $source = Db::name($this->source)->where(['id' => $id])->find();
            empty($source) && $this->error('编辑失败，请稍候再试！');

            Db::transaction(function () use ($data, $id, $source) {
                $where = ['id' => $id];
                Db::name($this->source)->where($where)->update($data);

            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('编辑成功！', "");
    }

    /**
     * 删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->source)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    /**
     * 禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (DataService::update($this->source)) {
            $this->success("禁用成功！", '');
        }
        $this->error("禁用失败，请稍候再试！");
    }

    /**
     * 禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->source)) {
            $this->success("启用成功！", '');
        }
        $this->error("启用失败，请稍候再试！");
    }

    /**
     * 活动二维码
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function qrcode()
    {
        $id = $this->request->get('id');
        $source = Db::name($this->source)->where(['id' => $id])->find();
        $ewm_url = urlencode("http://vote.sheyingtg.com/?source={$source['tag']}");
        return $this->fetch('qrcode', [
            'ewm_url' => $ewm_url,
        ]);

    }
}
